<template>
	<el-col :span="span" :xs="xs" :sm="sm" :md="md">
		<el-form-item :label="label" :label-width="labelWidth">
			<el-select
				v-model="internalValue"
				:placeholder="placeholder"
				clearable
			>
				<el-option
					v-for="item in options"
					:key="item.key"
					:label="item.label"
					:value="item.key"
				/>
			</el-select>
		</el-form-item>
	</el-col>
</template>

<script setup lang="ts">
import {PropType, ref, watch} from 'vue'

type OptionType = { key: string; label: string }

const props = defineProps({
	label: {type: String, required: true},
	options: {type: Array as () => OptionType[], default: () => []},
	modelValue: {type: String as PropType<string | null>, default: null},
	placeholder: {type: String as PropType<string | null>, default: null},
	labelWidth: {type: String, default: '100px'},
	span: {type: Number, default: 6},
	xs: {type: Number, default: 24},
	sm: {type: Number, default: 12},
	md: {type: Number, default: 6},
})

const emit = defineEmits<{
	(e: 'update:modelValue', value: string | null): void
}>()

// 内部响应式值，保证 v-model 可以使用 null
const internalValue = ref<string | null>(props.modelValue)

watch(
	() => props.modelValue,
	val => {
		internalValue.value = val
	}
)

watch(internalValue, val => {
	emit('update:modelValue', val)
})
</script>
